<template>
    <el-card>
        <!-- 搜索区 -->
        <el-form inline>
            <el-form-item size="small">
                <el-input v-model="inputUserName" placeholder="用户名" size="small"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="small" icon="el-icon-search" @click="searchUser">查询</el-button>
                <el-button size="small" @click="resetUser">清空</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮区 -->
        <el-button type="primary" size="small" @click="addUser">添加</el-button>
        <el-button type="danger" size="small" :disabled="!deleteAll.length" @click="deleteAllUser">批量删除</el-button>
        <!-- 表格区 -->
        <el-table border class="mt-20" :data="pageData" @selection-change="selectionChange">
            <el-table-column type="selection" width="55px"></el-table-column>
            <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
            <el-table-column label="用户名" width="150px" prop="username"></el-table-column>
            <el-table-column label="用户昵称" prop="nickName"></el-table-column>
            <el-table-column label="角色列表" width="200px" prop="roleName"></el-table-column>
            <el-table-column label="创建时间" width="180px" prop="gmtCreate"></el-table-column>
            <el-table-column label="更新时间" width="180px" prop="gmtModified"></el-table-column>
            <el-table-column label="操作" width="200px" fixed="right">
                <template #default="{ $index, row }">
                    <el-button size="mini" type="info" icon="el-icon-user" @click="handleUser($index, row)"
                        title="分配角色"></el-button>
                    <el-button size="mini" type="primary" icon="el-icon-edit-outline" @click="handleEdit($index, row)"
                        title="修改用户"></el-button>
                    <el-popconfirm :title='`确定删除${row.username}吗?`' @confirm="handleDelete($index, row)">
                        <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete"
                            title="删除用户"></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
            :page-sizes="[5, 10, 20, 30]" :page-size="limit" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            class="mt-20">
        </el-pagination>

        <!-- 添加弹出框 -->
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible" top="0px">
            <el-form :model="user" :rules="rules" ref="user">
                <el-form-item label="用户名" label-width="120px" prop="userName">
                    <el-input size="mini" v-model="user.userName"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" label-width="120px">
                    <el-input size="mini" v-model="user.nickName"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" label-width="120px" prop="password">
                    <el-input size="mini" v-model="user.password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm('user')" size="small">取 消</el-button>
                <el-button type="primary" @click="submitForm('user')" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 删除弹出框 -->
        <el-dialog :visible.sync="deleteVisable" width="20%">
            <span>确认删除吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteVisable = false">取 消</el-button>
                <el-button type="primary" @click="sureDeleteAll">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色弹出框 -->
        <el-dialog title="设置角色" :visible.sync="RoleVisible" top="0px">
            <el-form>
                <el-form-item label="用户名" label-width="80px">
                    <el-input size="mini" disabled v-model="RoleUserName"></el-input>
                </el-form-item>
                <el-form-item label="角色列表" label-width="80px">
                    <!-- 多选框区域 -->
                    <!-- label属性是该 checkbox 对应的值,label绑定的值,如果在group绑定的数组中,则选中-->
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="assignRolesId" @change="handleCheckedCRolesChange">
                        <el-checkbox v-for="role in allRolesList" :label="role.id"
                            :key="role.id">{{ role.roleName }}</el-checkbox>
                    </el-checkbox-group>

                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="RoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRole">确 定</el-button>
            </span>
        </el-dialog>


        <!-- 编辑弹出框 -->
        <el-dialog title="修改用户" :visible.sync="editVisiable" top="0px">
            <el-form :model="Editrule" :rules="rules" ref="ruleEdit">
                <el-form-item label="用户名" label-width="120px" prop="userName">
                    <el-input size="mini" v-model="Editrule.userName"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" label-width="120px">
                    <el-input size="mini" v-model="Editrule.nickName"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit('ruleEdit')" size="small">取 消</el-button>
                <el-button type="primary" @click="sureEdit('ruleEdit')" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script>

import userApi from '@/api/acl/user'
export default {
    name: "VUser",
    data() {
        return {
            inputUserName: '',    //input框的用户名
            searchUserName: '',   //搜索的用户名
            page: 1,     //当前页数
            limit: 5,     // 每页几条
            total: 0,     //总条数
            pageData: [],  //分页数据
            dialogFormVisible: false,  // 添加的弹框
            user: {
                userName: '',   // 添加用户的用户名
                nickName: '',    //用户昵称
                password: ''     // 用户密码
            },
            //表单验证
            rules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, message: '用户名不少于3字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, message: '密码不少于6位', trigger: 'blur' }
                ]
            },
            deleteAll: [],      //表格选中的数
            deleteVisable: false, //控制删除框

            userId: '',     //用户id
            RoleVisible: false,  //角色控制弹框
            RoleUserName: '',    //分配角色的input
            allRolesList: [],   //所有用户角色列表
            assignRolesId: [],  //某用户的角色列表的id
            isIndeterminate: '',  // 半选状态
            checkAll: false,  //全选框全选

            editVisiable: false,  //修改用户弹框
            Editrule: {             //编辑用户
                userName: '',
                nickName: ''
            },
            UserRow: {}    //一条用户
        }
    },
    methods: {
        //确认分配角色
        async saveRole() {
            //组织参数
            let { userId, assignRolesId } = this
            const roleId = assignRolesId.join(',')
            //发送请求
            await userApi.assignRoles(userId, roleId)
            this.RoleVisible = false
            this.getData()
            this.$message.success('保存成功')
        },
        // 设置角色
        async handleUser(index, row) {
            this.userId = row.id   //将用户id存起来
            this.RoleVisible = true
            this.RoleUserName = row.username   // input 展示内容
            // 获取角色列表
            let res = await userApi.getRoles(row.id)
            this.allRolesList = res.data.allRolesList
            this.assignRolesId = res.data.assignRoles.map(item => item.id)  //将用户独有的角色id存起来,上面渲染用
            this.isIndeterminate = res.data.assignRoles.length === 0 ? false : true  //如果某用户他有角色,就是半选
            this.checkAll = res.data.assignRoles.length === res.data.allRolesList ? true : false  //如果某用户的角色和全部的相等,就让全选框全选
        },
        //全选框改变
        handleCheckAllChange(val) {
            // console.log(val);   布尔值
            this.assignRolesId = val ? this.allRolesList.map(item => item.id) : []  //如果全选,就让该用户的角色列表等于总的角色
            this.isIndeterminate = false
            this.checkAll = val
        },
        //点击每一个的回调
        handleCheckedCRolesChange(value) {
            //console.log(value);   //代表选择的数据(id)加上最开始用户独有的角色id数组组成的新数组            
            let count = value.length
            this.checkAll = count === this.allRolesList.length ? true : false
            this.isIndeterminate = this.assignRolesId.length > 0 && this.assignRolesId.length < this.allRolesList.length
        },

        //修改用户
        handleEdit(index, row) {
            this.editVisiable = true
            this.Editrule.userName = row.username
            this.Editrule.nickName = row.nickName
            this.UserRow = row   //储存这一条用户,编辑时候用
        },
        //取消编辑
        cancelEdit(formName) {
            this.editVisiable = false
            this.$refs[formName].resetFields()
        },
        //确定编辑
        sureEdit(formName) {
            this.editVisiable = false
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    //重新组织参数
                    let newUser = {
                        ...this.UserRow,
                        username: this.Editrule.userName,
                        nickName: this.Editrule.nickName
                    }
                    //发请求
                    await userApi.update(newUser)
                    this.getData()
                    this.$message.success('编辑成功')
                }
            })
        },
        //删除用户
        async handleDelete(index, row) {
            await userApi.removeById(row.id)
            this.$message.success('删除成功')
            this.getData()
        },
        //每页几条的变化回调
        handleSizeChange(limitNo) {
            this.limit = limitNo
            this.getData()
        },
        // 当前页数变化回调
        handleCurrentChange(pageNo) {
            this.page = pageNo
            this.getData()
        },
        // 搜索用户
        searchUser() {
            this.searchUserName = this.inputUserName
            this.getData()
        },
        // 清空
        resetUser() {
            this.inputUserName = ''
            this.searchUserName = this.inputUserName
            this.getData()
        },
        // 添加用户
        addUser() {
            this.dialogFormVisible = true
            this.user = {
                userName: '',   // 添加用户的用户名
                nickName: '',    //用户昵称
                password: ''     // 用户密码
            }
        },
        // 确定新增
        async onSave() {

            // 收集数据
            const { userName, password, nickName } = this.user
            //发送请求
            try {
                await userApi.add({ username: userName, password, nickName })
                this.getData()
                this.$message.success('新增成功')
            } catch (error) {
                this.$message.error('网络错误')
            }
        },
        // 提交表单
        submitForm(formName) {
            this.dialogFormVisible = false
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    // 收集数据
                    const { userName, password, nickName } = this.user
                    //发请求
                    await userApi.add({ username: userName, password, nickName })
                    this.getData()
                    this.$message.success('新增成功')
                }
            })
        },
        // 取消表单
        resetForm(formName) {
            this.dialogFormVisible = false
            this.$refs[formName].resetFields()
        },

        //当点击表格选项的回调
        selectionChange(selection) {
            this.deleteAll = selection
        },
        //批量删除
        deleteAllUser() {
            this.deleteVisable = true
        },
        //确认删除全部
        async sureDeleteAll() {
            this.deleteVisable = false
            const ids = this.deleteAll.map(item => item.id)
            await userApi.removeUsers(ids)
            this.getData()
        },
        // 初始化数据
        async getData() {
            let res = await userApi.getPageList(this.page, this.limit, { username: this.searchUserName })
            if (res.code === 20000) {
                this.total = res.data.total
                this.pageData = res.data.items
            }
        }
    },
    //挂载
    mounted() {
        this.getData()
    }
}
</script>

<style lang="less" scoped></style>